/*
 * @Author: “ygnnli” “1585923072@qq.com”
 * @Date: 2024-08-04 11:52:42
 * @LastEditors: “ygnnli” “1585923072@qq.com”
 * @LastEditTime: 2024-08-04 15:58:07
 * @FilePath: /110/51/tcp_echo_server/MainClient.cc
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
#include <iostream>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include "Log.hpp"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <cstring>

// 输入格式不对
void Usage(std::string proc)
{
    std::cout << "Usage: \n\t" << proc << "loacl_ip  local_port\n"
              << std::endl;
}

// ./tcpclient serverip  serverport
int main(int arg, char *argv[])
{

    if (arg != 3)
    {
        Usage(argv[0]);
        exit(1);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    int sockfd = ::socket(AF_INET, SOCK_STREAM, 0); // 创建socket SOCK_STREAM----TCP
    if (sockfd < 0)
    {
        std::cerr << "socket error" << std::endl;
        exit(2);
    }

    // tcp client 要bind，不要显示的bind.
    struct sockaddr_in server;
    // 构建目标主机的socket信息
    memset(&server, 0, sizeof(server));                   // 清空server
    server.sin_family = AF_INET;                          // ipv4--网络字节序
    server.sin_port = htons(serverport);                  // 端口号--网络字节序
    server.sin_addr.s_addr = inet_addr(serverip.c_str()); // ip地址--网络字节序

    int n = connect(sockfd, (struct sockaddr *)&server, sizeof(server)); // 连接服务器
    if (n < 0)
    {
        std::cerr << "connect error" << std::endl;
        exit(3);
    }

    while (1)
    {
        std::cout << "Please Enter# ";
        std::string outstring;
        std::getline(std::cin, outstring); // 获取输入一行字符串

        ssize_t s = send(sockfd, outstring.c_str(), outstring.size(), 0); // 与write类似  多了一个flsges参数
        if (s > 0)
        {
            char inbuffer[1024];
            ssize_t m = recv(sockfd, inbuffer, sizeof(inbuffer) - 1, 0); // 与read类似  多了一个flsges参数
            if (m > 0)
            {
                inbuffer[m] = 0;
                std::cout << inbuffer << std::endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }

    ::close(sockfd); // 关闭socket

    return 0;
}